<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="rules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="设备名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="model.equName" placeholder="请输入设备名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="点位名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pointName">
              <a-select
                :showArrow="false"
                :showSearch="true"
                label-in-value
                :value="value"
                placeholder="请输入点位名称"
                style="width: 100%"
                :filter-option="false"
                :not-found-content="fetching ? undefined : null"
                @search="fetchUser"
                @change="handleChange"
                @focus="fetchUser"
              >
                <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                <a-select-option v-for="d in data" :key="d.pointNo">
                  {{ d.pointName }} ({{ d.pointNo }})
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="点位编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="model.pointCode" type="number" :disabled="true"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="管点编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pipPointNo">
              <a-input v-model="model.pipPointNo" type="string" :disabled="true"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="设备编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="equNo">
              <a-input v-model="model.equNo" placeholder="请输入设备编号" type="number"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="SIM卡号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="model.sim" placeholder="请输入SIM卡号" type="number"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="设备类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!-- <a-input v-model="model.equType" placeholder="请输入设备类型" style="width: 100%" /> -->
              <!-- <a-select v-model="model.equType">
                <a-select-option :value="1"> 液位仪</a-select-option>
                <a-select-option :value="2"> 水质监测</a-select-option>
                <a-select-option :value="3"> 流量计</a-select-option>
              </a-select> -->
              <JDictSelectTag v-model="model.equType" dictCode="ps_equ_type" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="补偿值" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!-- <j-date placeholder="请选择注册时间"  v-model="model.compensate" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" /> -->
              <a-input v-model="model.compensate" placeholder="请输入补偿值" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="设备归属状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group v-model="model.equBelong">
                <a-radio :value="1"> 租赁</a-radio>
                <a-radio :value="2"> 售卖</a-radio>
                <a-radio :value="3"> 临时</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
// import { validateDuplicateValue } from '@/utils/util'
import debounce from 'lodash/debounce'
import { getPointList } from '@api/point'

export default {
  name: 'EquipmentForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    this.lastFetchId = 0
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: [],
      url: {
        add: '/paishui/equipment/add',
        edit: '/paishui/equipment/edit',
        queryById: '/paishui/equipment/queryById'
      },
      // 校验规则
      rules: {
        pointCode: [
          { required: true, message: '点位编号不能为空', trigger: 'blur' }
          // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
        ],
        // pipPointNo: [
        //   { required: true, message: '管点编号不能为空', trigger: 'blur' }
        //   // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
        // ],
        equNo: [{ required: true, message: '设备编号不能为空', trigger: 'change' }],
        pointName: [{ required: true, message: '点位名称不能为空', trigger: 'blur' }]
      },
      //搜索框字段
      data: [],
      value: '',
      text: '',
      fetching: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'post'
          }
          console.log(this.model)
          switch (this.model.equBelong) {
            case '租赁':
              this.model.equBelong = 1
              break
            case '售卖':
              this.model.equBelong = 2
              break
            case '临时':
              this.model.equBelong = 3
              break
          }
          switch (this.model.onlintStatus) {
            case '未激活':
              this.model.equBelong = 1
              break
            case '在线':
              this.model.equBelong = 2
              break
            case '离线':
              this.model.equBelong = 3
              break
          }
          switch (this.model.equType) {
            case '液位计':
              this.model.equBelong = 1
              break
            case '水质监测':
              this.model.equBelong = 2
              break
            case '流量计':
              this.model.equBelong = 3
              break
          }
          console.log(this.model)
          httpAction(httpurl, this.model, method)
            .then(res => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    /*
     * 文本框值变化时回调
     * */
    fetchUser(value) {
      console.log('fetching user', value)
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.data = []
      this.fetching = true
      if (value == undefined) value = ''
      getAction(`/paishui/paishuiPointPos/list?pointName=*${value}*`).then(res => {
        this.data = res.result.records
        console.log('this.data======', this.data)
      })
    },
    /*
     * 选中 option，或 input 的 value 变化时
     * */
    handleChange(value, option) {
      console.log('value value', value)
      // console.log('value label',value.label.split('\n'))
      const str = value.label
      const trimmedStr = str.trim()
      console.log('trimmedStr=====', trimmedStr.split(' ')[0])
      this.model.pointName = trimmedStr.split(' ')
      this.model.pointCode = value.key
      this.getPointList(value.key)
      Object.assign(this, {
        value,
        data: [],
        fetching: false
      })
    },
    // 拿到点位编号获取管点编号
    async getPointList(value) {
      console.log(value, 8.25)
      const res = await getPointList({ associationPosPointNo: value })
      console.log(res.result.records, 8.25)
      this.model.pipPointNo = res.result.records[0].pipNo
      console.log('pipPoint/list', res.result.records[0].pipNo)
      this.$forceUpdate()
    }
  }
}
</script>
